import { useAuth } from '@clerk/nextjs'
import {
  Dropdown,
  DropdownTrigger,
  DropdownMenu,
  DropdownItem,
  Button,
  DropdownSection,
  Avatar
} from '@nextui-org/react'
import { usePathname, useRouter } from 'next/navigation'
import NextIcon from '../NextIcon'
import { RootContext } from '@/app/RootContext'
import React, { useEffect, useState } from 'react'
import { useUserProfile } from '@/hooks/auth/use-is-user-profile'

type MenuProps = {
  label: React.ReactNode
  key: string
  icon?: React.ReactNode
  description?: string
  children?: MenuProps[]
}
const UserMenu = ({ children }: { children: React.ReactNode }) => {
  const { userInfo } = RootContext.useContainer()

  const route = useRouter()
  const pathname = usePathname()
  const auth = useAuth()
  const isUserProfile = useUserProfile()

  const [selectedKeys, setSelectedKeys] = useState<Iterable<string>>(
    new Set([pathname])
  )

  const signOut = () => {
    auth.signOut({ redirectUrl: isUserProfile ? '/home' : pathname })
    localStorage.removeItem('doc-tree-select-post')
    localStorage.removeItem('doc-expand-keys')
  }

  const style = {
    className: 'mr-4',
    size: 16
  }

  const items: MenuProps[] = [
    {
      label: '账户',
      key: 'user',
      children: [
        {
          label: (
            <>
              <Avatar
                showFallback
                className="cursor-pointer dark:filter-none inline-block"
                src={userInfo?.imageUrl}
                fallback={userInfo?.username}
              />
              <span className="ml-4">{userInfo?.username}</span>
            </>
          ),
          key: '/user-profile'
        },
        {
          label: (
            <>
              <NextIcon type="yanzhengma" {...style} />
              安全
            </>
          ),
          key: '/user-profile/security'
        }
      ]
    },
    {
      label: 'sign',
      key: 'sign',
      children: [
        {
          label: (
            <>
              <NextIcon type="sgin-out" {...style} />
              退出
            </>
          ),
          key: 'sign-out'
        }
      ]
    }
  ]

  useEffect(() => {
    if (!!pathname) {
      setSelectedKeys(new Set([pathname]))
    }
  }, [pathname])

  return (
    <Dropdown>
      <DropdownTrigger>{children}</DropdownTrigger>

      <DropdownMenu
        aria-label="Static Actions"
        selectionMode="single"
        variant="flat"
        disallowEmptySelection
        selectedKeys={selectedKeys}
        onSelectionChange={p => {
          if (p?.anchorKey && p?.anchorKey !== 'sign-out') {
            setSelectedKeys([p.anchorKey])
            route.push(p.anchorKey)
          } else {
            signOut()
          }
        }}
      >
        {items?.map((item, index) => {
          return (
            <DropdownSection
              key={item?.key}
              title={item?.label as any}
              showDivider={item.key !== 'sign'}
            >
              {
                item?.children?.map(child => {
                  if (child?.key === 'sign-out') {
                    return (
                      <DropdownItem
                        key={child.key}
                        className="text-danger"
                        color="danger"
                      >
                        {child?.label}
                      </DropdownItem>
                    )
                  }

                  return (
                    <DropdownItem
                      key={child.key}
                      className={
                        child.key === '/document/project' ? 'text-primary' : ''
                      }
                      color={
                        child.key === '/document/project'
                          ? 'primary'
                          : 'default'
                      }
                    >
                      {child?.label}
                    </DropdownItem>
                  )
                }) as any[]
              }
            </DropdownSection>
          )
        })}
      </DropdownMenu>
    </Dropdown>
  )
}

export default UserMenu
